package main

import (
	"fmt"
	"github.com/spf13/cobra"
	"log"
	"net"
	"os"
	"strconv"
	"svs/cmd"
	"svs/global"
	"svs/initialize"
	"svs/util"
)

const (
	FOREVER = "forever"
)

var rootCmd *cobra.Command

func init() {
	rootCmd = &cobra.Command{
		Use:        "svs",
		Aliases:    nil,
		SuggestFor: nil,
		Short:      "svs",
		GroupID:    "",
		Long:       "",
		Run: func(cmd *cobra.Command, args []string) {
			if len(args) == 0 || (len(args) > 0 && !util.InArray(args[0], global.SupportCmdSlice)) {
				log.Println("不带参数启动将正常启动http服务")
				HttpServer(args)
			}
		},
	}
	rootCmd.Version = "1.0.0"
	rootCmd.AddCommand(cmd.Algorithm)
	fmt.Println("main init")
}
func main() {
	//defer func() {
	//	if err := recover(); err != nil {
	//		fmt.Println(err.(error).Error())
	//	}
	//}()
	if err := rootCmd.Execute(); err != nil {
		fmt.Println("程序启动失败", err.Error())
		os.Exit(1)
	}
}

func HttpServer(args []string) {
	global.VP = initialize.InitViper("./config.yaml")
	global.DB = initialize.Gorm()
	global.CACHE = util.NewGCache()
	var forever bool

	if len(args) > 0 && args[0] == FOREVER {
		forever = true
	}
	if forever {
		for {
			s := initialize.StripSlice(os.Args, "-"+FOREVER)
			cmd := initialize.SubProcess(s)
			cmd.Wait()
		}
		os.Exit(0)
	} else {
		fmt.Printf("[*] Service running in PID: %d PPID: %d\n", os.Getpid(), os.Getppid())
	}
	ln, err := net.Listen("tcp", ":"+strconv.Itoa(int(global.CONFIG.Gin.Port)))
	if err != nil {
		fmt.Println("端口被占用")
		return
	} else {
		ln.Close()
	}
	s, _ := initialize.NewServer()
	s.Start()
}
